package com.huanglj.himalaya.presenters;

import android.content.Context;
import android.content.SharedPreferences;

import com.huanglj.himalaya.base.BaseApplication;
import com.huanglj.himalaya.interfaces.IPlayerCallBack;
import com.huanglj.himalaya.interfaces.IPlayerPresenter;
import com.huanglj.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis;
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.advertis.IXmAdsStatusListener;
import com.ximalaya.ting.android.opensdk.player.constants.PlayerConstants;
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;

public class PlayerPresenter implements IPlayerPresenter, IXmAdsStatusListener, IXmPlayerStatusListener {

    private static final String TAG = "PlayerPresenter";
    private final XmPlayerManager mPlayerManager;
    List<IPlayerCallBack> mCallBacks = new ArrayList<>();
    private List<Track> mList;
    private int mStartIndex;
    private Track mCurrentTrack;
    private Track mStartTrack;
    private int mCurrentIndex = 0;
    private SharedPreferences mPlayModesp = null;

    public static final int PLAY_MODE_LIST_INT = 0;
    public static final int PLAY_MODE_LIST_LOOP_INT = 1;
    public static final int PLAY_MODE_RANDOM_INT = 2;
    public static final int PLAY_MODE_SINGLE_LOOP_INT = 3;

    public static final String PLAY_NODE_NAME = "PlayMode";
    public static final String PLAY_NODE_KEY = "CurrentPlayMode";
    private XmPlayListControl.PlayMode mModeByInt;
    private boolean isReverse = false;
    private final HistoryPresenter mHistoryPresenter;


    private PlayerPresenter(){
        LogUtil.d(TAG,BaseApplication.getContext()+"");
        mPlayerManager = XmPlayerManager.getInstance(BaseApplication.getContext());
        //广告相关的接口物料回调
        mPlayerManager.addAdsStatusListener(this);
        //注册播放器相关的接口
        mPlayerManager.addPlayerStatusListener(this);
        if (BaseApplication.getContext()!= null){
            mPlayModesp = BaseApplication.getContext().getSharedPreferences(PLAY_NODE_NAME,Context.MODE_PRIVATE);
        }
        mHistoryPresenter = HistoryPresenter.getInstance();
    }

    private static PlayerPresenter sInstance = null;

    public static PlayerPresenter getPlayerPresenter(){
        if (sInstance == null) {
            synchronized (PlayerPresenter.class){
                if (sInstance == null) {
                    sInstance = new PlayerPresenter();
                }
            }
        }
        return sInstance;
    }
    private boolean isPlayListSet = false;
    public void setPlayList(List<Track>list,int startIndex){
        mList = list;
        if (mPlayerManager != null) {
            mPlayerManager.setPlayList(list,startIndex);
            isPlayListSet = true;
            mStartTrack = list.get(startIndex);
            mStartIndex = startIndex;
        }
    }

    @Override
    public void play() {
        if (mPlayerManager != null && mCallBacks.size() == 1) {
            mPlayerManager.play(1);
        }{
            mPlayerManager.play();
        }
    }

    @Override
    public void pause() {
        //设置暂停后，接口状态变成onPlayPause，然后接口通知ui变化
        if (mPlayerManager != null) {
            mPlayerManager.pause();

        }
    }

    @Override
    public void stop() {
        if (mPlayerManager != null) {
            mPlayerManager.stop();

        }
    }

    @Override
    public void playPrevious() {
        if (mPlayerManager != null) {
            mPlayerManager.playPre();

        }
    }

    @Override
    public void playNext() {
        if (mPlayerManager != null) {
            mPlayerManager.playNext();

        }
    }

    @Override
    public void switchPlayMode(XmPlayListControl.PlayMode mode) {
        if (mPlayerManager != null) {
            mPlayerManager.setPlayMode(mode);
            for (IPlayerCallBack callBack : mCallBacks) {
                callBack.onPlayModeChange(mode);
            }
            //保存缓存
            SharedPreferences.Editor editor = mPlayModesp.edit();
            editor.putInt(PLAY_NODE_KEY,getIntByPlayMode(mode));
            editor.apply();
        }
    }
    private int getIntByPlayMode(XmPlayListControl.PlayMode mode){
        switch (mode){
            case PLAY_MODEL_LIST:
                return PLAY_MODE_LIST_INT;
            case PLAY_MODEL_LIST_LOOP:
                return PLAY_MODE_LIST_LOOP_INT;
            case PLAY_MODEL_RANDOM:
                return PLAY_MODE_RANDOM_INT;
            case PLAY_MODEL_SINGLE_LOOP:
                return PLAY_MODE_SINGLE_LOOP_INT;
        }
        return PLAY_MODE_LIST_INT;
    }
    private XmPlayListControl.PlayMode getModeByInt(int i){
        switch (i){
            case PLAY_MODE_LIST_INT:
                return PLAY_MODEL_LIST;
            case PLAY_MODE_LIST_LOOP_INT:
                return PLAY_MODEL_LIST_LOOP;
            case PLAY_MODE_RANDOM_INT:
                return PLAY_MODEL_RANDOM;
            case PLAY_MODE_SINGLE_LOOP_INT:
                return PLAY_MODEL_SINGLE_LOOP;

        }
        return PLAY_MODEL_LIST;
    }
    public void playIndex(){
        if(mCallBacks.size() == 1){
            playByIndex(0);
        }
    }

    @Override
    public void getPlayList() {
        List<Track> playList = mPlayerManager.getPlayList();
        if (mCallBacks != null) {
            for (IPlayerCallBack callBack : mCallBacks) {
                callBack.onListLoaded(playList);
            }
        }
        int currentIndex = mPlayerManager.getCurrentIndex();
    }

    @Override
    public void playByIndex(int index) {
        mPlayerManager.play(index);

    }

    @Override
    public void seekTo(int progress) {
        mPlayerManager.seekTo(progress);
    }

    @Override
    public boolean isPlay() {
        //默认返回播放
        return mPlayerManager.isPlaying();
    }

    @Override
    public void reversePlayList() {
        List<Track> playList = mPlayerManager.getPlayList();
        Collections.reverse(playList);
         isReverse = !isReverse;
        mCurrentIndex = playList.size() - 1 - mCurrentIndex;
        mPlayerManager.setPlayList(playList,mCurrentIndex);
        mCurrentTrack = (Track) mPlayerManager.getCurrSound();
        for (IPlayerCallBack callBack : mCallBacks) {
            callBack.onListLoaded(playList);
            callBack.onTrackUpdate(mCurrentTrack,mCurrentIndex);
        }
    }

    @Override
    public int getCurrentIndex() {
        return mPlayerManager.getCurrentIndex();
    }

    @Override
    public void unRegisterViewCallBack(IPlayerCallBack iPlayerCallBack) {
        if (!mCallBacks.contains(iPlayerCallBack)) {
            mCallBacks.remove(iPlayerCallBack);
        }
    }

    @Override
    public void registerViewCallBack(IPlayerCallBack iPlayerCallBack) {
        if (!mCallBacks.contains(iPlayerCallBack)) {
            mCallBacks.add(iPlayerCallBack);
        }
        LogUtil.d(TAG,"开始注册播放事件");
        //需要记录当前模式
        getPlayList();
        iPlayerCallBack.onTrackUpdate(mStartTrack, mStartIndex);
        int anInt = mPlayModesp.getInt(PLAY_NODE_KEY, PLAY_MODE_LIST_INT);
        mModeByInt = getModeByInt(anInt);
        iPlayerCallBack.onPlayModeChange(mModeByInt);
        //mCallBacks.clear();


    }
    //====================广告相关的回调-start========================
    @Override
    public void onStartGetAdsInfo() {
        LogUtil.d(TAG,"onStartGetAdsInfo");
    }

    @Override
    public void onGetAdsInfo(AdvertisList advertisList) {

    }

    @Override
    public void onAdsStartBuffering() {

    }

    @Override
    public void onAdsStopBuffering() {

    }

    @Override
    public void onStartPlayAds(Advertis advertis, int i) {

    }

    @Override
    public void onCompletePlayAds() {

    }

    @Override
    public void onError(int i, int i1) {

    }
//============================广告相关的接口回调 stop==================================
    //==========================播放相关的接口回调 start============================================
    @Override
    public void onPlayStart() {
        LogUtil.d(TAG,"onPlayStart");
        if (mCallBacks != null) {
            for (IPlayerCallBack callBack : mCallBacks) {
                callBack.onPlayStart();
            }
        }
    }

    @Override
    public void onPlayPause() {
        if (mCallBacks != null) {
            for (IPlayerCallBack callBack : mCallBacks) {
                callBack.onPlayPause();
            }
        }
        LogUtil.d(TAG,"onPlayPause");
    }

    @Override
    public void onPlayStop() {
        if (mCallBacks != null) {
            for (IPlayerCallBack callBack : mCallBacks) {
                callBack.onPlayStop();
            }
        }
        LogUtil.d(TAG,"onPlayStop");
    }

    @Override
    public void onSoundPlayComplete() {
        LogUtil.d(TAG,"onSoundPlayComplete");
    }

    @Override
    public void onSoundPrepared() {
        LogUtil.d(TAG,"onSoundPrepared");
        mPlayerManager.setPlayMode(mModeByInt);
        if (mPlayerManager.getPlayerStatus() == PlayerConstants.STATE_PREPARED) {
            mPlayerManager.play();
        }
    }

    @Override
    public void onSoundSwitch(PlayableModel lastModel, PlayableModel curModel) {
//        //不推荐
//        if (curModel.getKind().equals("track")) {
//            Track currentTrack = (Track) curModel;
//        }
        if (curModel instanceof Track) {
            mCurrentTrack = (Track) curModel;
        }
        mHistoryPresenter.addHistory(mCurrentTrack);
        LogUtil.d(TAG,"onSoundSwitch");
        if (mCallBacks != null ) {
            for (IPlayerCallBack callBack : mCallBacks) {
                mCurrentIndex = mPlayerManager.getCurrentIndex();
                callBack.onTrackUpdate(mCurrentTrack,mCurrentIndex);
            }
        }
    }

    @Override
    public void onBufferingStart() {
        LogUtil.d(TAG,"onBufferingStart");
    }

    @Override
    public void onBufferingStop() {
        LogUtil.d(TAG,"onBufferingStop");
    }

    @Override
    public void onBufferProgress(int percent) {
        LogUtil.d(TAG,"onBufferProgress"+percent);
    }

    @Override
    public void onPlayProgress(int currPos, int duration) {
        //事件单位为ms
        //LogUtil.d(TAG,"onPlayProgress: 当前进度: "+ currPos + ",总进度: " + duration );
        for (IPlayerCallBack callBack : mCallBacks) {
            callBack.onProgressChange(currPos,duration);
        }
    }

    @Override
    public boolean onError(XmPlayerException e) {
        LogUtil.d(TAG,"onError");
        return false;
    }

    public boolean hasPlayList() {
        return isPlayListSet;
    }
    //===================播放相关的回调-stop===============================

}
